package org.bringer.dao.hibernate;

import java.util.List;

import org.bringer.dao.AccountDao;
import org.bringer.dao.SearchException;
import org.bringer.model.Account;
import org.bringer.model.User;
import org.hibernate.Query;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Repository;

/**
 * This class interacts with Hibernate session to save/delete and
 * retrieve User objects.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 *   Modified by <a href="mailto:dan@getrolling.com">Dan Kibler</a>
 *   Extended to implement Acegi UserDetailsService interface by David Carter david@carter.net
 *   Modified by <a href="mailto:bwnoll@gmail.com">Bryan Noll</a> to work with
 *   the new BaseDaoHibernate implementation that uses generics.
 *   Modified by jgarcia (updated to hibernate 4)
*/
@Repository
public class AccountDaoHibernate extends GenericDaoHibernate<Account, Long> implements AccountDao {

    /**
     * Constructor that sets the entity to User.class.
     */
    public AccountDaoHibernate() {
        super(Account.class);
    }
	

	@Override
	public Account getAccountByIban(String iban) {
		// TODO Auto-generated method stub
		List<Account> accounts = getSession().createCriteria(Account.class).add(Restrictions.eq("ibanCode", iban)).list();
        if (accounts == null || accounts.isEmpty()) {
            throw new SearchException("Accounts not founded with that criteria:"+iban);
        } else {
            return (Account) accounts.get(0);
        }		
	}

	@Override
	public List<Account> getAccountsByUser(User user) {
		 Query qry = getSession().createQuery("from Account where owner_id=:o_id");
		 qry.setParameter("o_id", user.getId());
		 List<Account> accounts=qry.list();
		 if (accounts == null || accounts.isEmpty()) {
	            throw new SearchException("Accounts not founded with that criteria (user):"+user.getId());
	        } else {
	            return  accounts;
	        }		
	}

	@Override
	public List<Account> getAccountsByDescription(String desc) {
		List<Account> accounts = getSession().createCriteria(Account.class).add(Restrictions.like("description", desc, MatchMode.ANYWHERE)).list();
        if (accounts == null || accounts.isEmpty()) {
            throw new SearchException("Accounts not founded with that criteria:"+desc);
        } else {
            return accounts;
        }		
	}


	@Override
	public void removeByIban(String iban) {
		// TODO Auto-generated method stub
		List<Account> accounts = getSession().createCriteria(Account.class).add(Restrictions.eq("ibanCode", iban)).list();
        if (accounts == null || accounts.isEmpty()) {
            throw new SearchException("Accounts not founded with that criteria:"+iban);
        } else {
            remove((Account) accounts.get(0));
        }		
	}

}
